import subprocess
import tempfile
import os
import stat

def _is_malicious(code: str) -> bool:
    """
    A simple check for potentially malicious commands in the code.
    This is not a foolproof security measure, but a basic deterrent.
    """
    malicious_keywords = [
        "rm -rf",
        "mkfs",
        "dd if=/dev/zero",
        ":(){:|:&};:",  # Fork bomb
        "shutdown",
        "reboot",
        "mv / /dev/null",
    ]
    for keyword in malicious_keywords:
        if keyword in code:
            return True
    return False

def execute_in_sandbox(code: str, timeout: int = 60) -> str:
    """在模拟的沙箱环境中执行Python代码。
    这是更强大的基于Docker的沙箱的占位符。
    目前，它使用临时文件和具有基本安全性的子进程。

    Args:
        code (str): 要执行的Python代码。
        timeout (int): 最长执行时间（秒）。

    Returns:
        str: 执行代码的输出，或错误消息。
    """
    if _is_malicious(code):
        return "Error: Malicious code detected. Execution aborted."

    with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.py') as temp_file:
        temp_file.write(code)
        temp_file_path = temp_file.name

    # The os.chmod call is often problematic on Windows and might not be necessary
    # with the default permissions provided by tempfile.
    # os.chmod(temp_file_path, stat.S_IRUSR | stat.S_IXUSR)

    try:
        # Use a restricted Python interpreter if available, or just python
        # For a real sandbox, this would be a Docker run command
        command = ["python", temp_file_path]
        
        process = subprocess.run(
            command,
            capture_output=True,
            text=True,
            timeout=timeout,
            check=False # Do not raise an exception for non-zero exit codes
        )

        if process.returncode != 0:
            return f"Sandbox execution failed with exit code {process.returncode}.\nStdout: {process.stdout}\nStderr: {process.stderr}"
        else:
            return process.stdout
    except subprocess.TimeoutExpired:
        return f"Sandbox execution timed out after {timeout} seconds."
    except Exception as e:
        return f"An unexpected error occurred during sandbox execution: {e}"
    finally:
        # Clean up the temporary file
        if os.path.exists(temp_file_path):
            os.remove(temp_file_path)


